
/**
 * This file is part of Wireless TransFer.
 *
 *   Wireless TransFer is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *	
 *   Wireless TransFer is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with Wireless TransFer.  If not, see <http://www.gnu.org/licenses/>.
 *	 
 *	 Copyright (C) 2011
 *   @author christofferP
 */
package com.wirelesstransfer.server.WIFI.handlers;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import com.wirelesstransfer.connection.ServerActions;
import com.wirelesstransfer.server.ConnectedClients.ConnectedClient;
import com.wirelesstransfer.server.ConnectedClients.ConnectedClientsHandler;

import android.util.Log;

/**
 * SendFileHandler sends a specific file to the calling
 * client.
 * 
 * Headers needed:
 * sessionId
 * 
 * @author christofferp
 */

public class SendFileHandler extends AbstractHandler{

	private String TAG = "SendFileHandler";

	private String clientId;
	private ConnectedClientsHandler connectedClientsHandler;
	private ConnectedClient client;
	private File file;

	private final int BUFFERSIZE = 65536;

	public void handle(String target,
			Request baseRequest,
			HttpServletRequest request,
			HttpServletResponse response) 
	throws IOException, ServletException {

		Log.v(TAG, "Handling send");


		connectedClientsHandler = ConnectedClientsHandler.getInstance();
		baseRequest.setHandled(true);

		//mimetyes for streams
		response.setContentType("application/octet-stream");

		clientId = request.getHeader(ServerActions.SESSIONID);
		client = connectedClientsHandler.getClientById(clientId);
		Log.v(TAG, "cilent id " + client.getId());

		if(client != null){
			if(client.nextFile()){

				file = client.getCurrentFile();
				Log.v(TAG, "Sending file: " + file.getAbsolutePath() + " Size: " + file.length());

				response.addHeader(ServerActions.FILEPATH, file.getAbsolutePath());
				response.addHeader(ServerActions.FILESIZE, "" + file.length());

				OutputStream os = response.getOutputStream();

				sendFile(file,os);

				Log.v(TAG, "File sent");
				response.setStatus(HttpServletResponse.SC_OK);

			}
		}
		else{
			Log.v(TAG, "sessionId NOT OK");
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		}
	}
	/**
	 * Sends a file through a outputstrem
	 * @param file to be sent
	 * @param os stream to send to
	 * @throws IOException
	 */
	private void sendFile(File file, OutputStream os){
		try {
			byte [] buffer  = new byte [BUFFERSIZE];
			FileInputStream fis = new FileInputStream(file);

			int len = 0;
			while((len = fis.read(buffer)) > -1){
				os.write(buffer, 0, len);
			}
			os.flush();
			os.close();

		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
	}
}